import cv2

cap = cv2.VideoCapture(0)


# 检测人脸
def face_detection(img):
    classifier = cv2.CascadeClassifier("./haarcascades/haarcascade_frontalface_alt2.xml")
    faces = classifier.detectMultiScale(
        image=img,
        scaleFactor=1.2,
        minNeighbors=5,
        flags=0,
        minSize=[50, 50],
        maxSize=[200, 200]
    )

    for face in faces:
        x, y, w, h = face
        cv2.rectangle(img, (x, y), (x + w, y + h), color=(0, 0, 255), thickness=2)


while True:
    flags, frame = cap.read()
    if flags is False:
        print("摄像头获取图像失败")
        break
    # 检测人脸
    face_detection(frame)
    cv2.imshow("frame", frame)
    if cv2.waitKey(1) == ord(" "):
        break

cap.release()
cv2.destroyAllWindows()
